package de.lgohlke.helper;

import java.util.concurrent.TimeoutException;

/**
 * <p>TimeOutHelper class.</p>
 *
 * @author lars
 * @version $Id: $
 */
public final class TimeOutHelper
{
  private TimeOutHelper()
  {
    // ok
  }

  /**
   * <p>waitForActionOrTimeout.</p>
   *
   * @param timeout
   *          - maximale Zeit in ms, die geprüft wird (mit mehreren Itnervallen)
   * @param waitIntervall
   *          - Überprüfungsintervall in ms
   * @param action
   *          - die Prüfung
   * @throws java.lang.InterruptedException if any.
   * @throws java.util.concurrent.TimeoutException if any.
   */
  public static void waitForActionOrTimeout(final long timeout, final long waitIntervall, final WaitForAction action) throws InterruptedException,
      TimeoutException
  {
    long waitCounter = 0;
    boolean found = false;

    while (!found)
    {
      found = action.doAction(waitCounter);

      if (!found)
      {
        Thread.sleep(waitIntervall);

        waitCounter += waitIntervall;

        if (waitCounter >= timeout)
        {
          throw new TimeoutException("Ereignis ist nicht eingetreten");
        }
      }
    }
  }
}
